<?php
/**
 * Created by PhpStorm.
 * User: shaowei
 * Date: 2018/12/22
 * Time: 下午2:07
 */


namespace App\Http\Model;

use Illuminate\Support\Facades\Redis;

class RoomWaitbit extends Base
{
    private $redis_room_waitbit_map_key = "ROOM:WAITBITMAP:"; //ROOM:WAITBIT:{room_id}
    private $redis_room_waitbit_list_key = "ROOM:WAITBITLIST:"; //ROOM:WAITBIT:{room_id} 排序使用
    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }


    /**
     * 添加用户
     * @param $room_id
     * @param $user_id
     * @param $type   0.没有守护 1.青铜 2.白银 3.黄金
     * @return mixed
     */
    public function add_user($room_id, $user_id, $type = 0){
        $map_key = $this->redis_room_waitbit_map_key . $room_id;
        $list_key = $this->redis_room_waitbit_list_key . $room_id;
        if (Redis::HEXISTS($map_key, $user_id)){
            return false;
        }
        Redis::HSET($map_key, $user_id, $type);
        Redis::RPUSH($list_key, $user_id);
        return true;
    }

    /**
     * 获取用户列表
     * @param $room_id
     * @return array|null
     */
    public function get_usersids($room_id){
        $map_key = $this->redis_room_waitbit_map_key . $room_id;
        $list_key = $this->redis_room_waitbit_list_key . $room_id;
        $map_users = Redis::HGETALL($map_key);
        if (empty($map_users)){
            return [];
        }
        $list_users = Redis::LRANGE($list_key, 0, -1);
        $ret = [];
        for ($i = 0; $i < count($list_users); $i++){
            $item = [];
            $item['user_id'] = intval($list_users[$i]);
            $item['guard_type'] = intval($map_users[$list_users[$i]]);
            array_push($ret, $item);
        }
        return $ret;
    }


    /**
     * 获取排麦类型
     * @param $room_id
     * @param $user_id
     * @return bool
     */
    public function get_guard_type($room_id, $user_id){
        $map_key = $this->redis_room_waitbit_map_key . $room_id;
        $ret = Redis::HGET($map_key, $user_id);
        if ($ret == null){
            return null;
        }
        return intval($ret);

    }


    /**
     * 删除用户
     * @param $room_id
     * @param $user_id
     * @return boolean
     */
    public function del_user($room_id, $user_id){
        $map_key = $this->redis_room_waitbit_map_key . $room_id;
        $list_key = $this->redis_room_waitbit_list_key . $room_id;
        Redis::LREM($list_key, 0, $user_id);
        Redis::HDEL($map_key, $user_id);
        return true;
    }


    /**
     * 清理所有用户
     * @param $room_id
     * @return bool
     */
    public function del_users($room_id){
        $map_key = $this->redis_room_waitbit_map_key . $room_id;
        $list_key = $this->redis_room_waitbit_list_key . $room_id;
        Redis::DEL($list_key);
        Redis::DEL($map_key);
        return true;
    }

}

